package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/user/addressBook")
@RestController
@Api(tags = "地址相关接口")
public class AddressBookController {

    private static final Logger log = LoggerFactory.getLogger(AddressBookController.class);

    @Autowired
    private AddressBookService addressBookService;

    /**
    * 新增地址
    * @param addressBook
    * @return Result
    */
    @PostMapping
    @ApiOperation("新增地址")
    public Result addAddress(@RequestBody AddressBook addressBook){
        log.info("新增地址：{}",addressBook);
        addressBookService.addAddress(addressBook);
        return Result.success();
    }

    /**
    * 查询全部地址
    * @param
    * @return Result<AddressBook>
    */
    @GetMapping("/list")
    @ApiOperation("查询全部地址")
    public Result<List<AddressBook>> list(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(addressBook);
        return Result.success(list);
    }

    /**
    * 查询默认地址
    * @param
    * @return Result<AddressBook>
    */
    @GetMapping("/default")
    public Result<AddressBook> defaultAddress(){
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
         List<AddressBook> list = addressBookService.defaultAddress(addressBook);
        if (list != null && list.size() == 1) {
            return Result.success(list.get(0));
        }
        return Result.error("没有查询到默认地址");
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();
    }

    /**
    * 根据id查询地址
    * @param id
    * @return Result<List<AddressBook>>
    */
    @GetMapping("/{id}")
    public Result<AddressBook> selectById(@PathVariable Long id){
        List<AddressBook> list = addressBookService.selectById(id);
        AddressBook addressBook = list.get(0);
        return Result.success(addressBook);
    }

    /**
    * 设置默认地址
    * @param addressBook
    * @return Result
    */
    @PutMapping("/default")
    public Result setDefaultAddress(@RequestBody AddressBook addressBook){
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteById(@RequestParam Integer id){
        addressBookService.deleteById(id);
        return Result.success();
    }
}
